<!-- 黑色科技风地图 -->
<template>
  <div id="mapbox-container"></div>
</template>

<script setup>
import { onMounted, getCurrentInstance } from 'vue'
import mapboxgl from '../../components/mapbox/mapbox.js'
import U from 'mapbox-gl-utils'
import axios from 'axios'
import api from '../../api/geoserver'
import * as turf from '@turf/turf'
// import MapboxDraw from '@mapbox/mapbox-gl-draw'
// import MapboxLanguage from '@mapbox/mapbox-gl-language'
import { Threebox, THREE } from 'threebox-plugin'

defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
let map = null

let mapconfig = null
// const emit = defineEmits(['onload'])
const { proxy } = getCurrentInstance()
const path = import.meta.env.VITE_APP_PATH

onMounted(() => {
  loadConfig()
})

// 同步加载底图配置信息
async function loadConfig() {
  const config = await axios.get(import.meta.env.VITE_APP_PATH + 'config/config.json').catch((err) => console.log(err))
  const style = await axios.get(import.meta.env.VITE_APP_PATH + 'config/dark-v11.json').catch((err) => console.log(err))
  console.log(config.data, style)
  mapconfig = proxy.$root.$mapconfig = config.data.schoolMap
  initMap(style.data)
}

// 根据配置信息初始化地图
function initMap(style) {
  const option = mapconfig.campus[1]
  // 初始化创建mapbox地图

  map = new mapboxgl.Map({
    container: 'mapbox-container',
    style: style,
    // style: 'mapbox://styles/mapbox/dark-v11',
    center: option.center,
    zoom: option.zoom,
    pitch: 56,
    bearing: -35.2
  })
  // mapboxgl.setRTLTextPlugin(
  //   'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js'
  // )
  // map.addControl(new MapboxLanguage({defaultLanguage: 'zh-Hans'}))
  // map.addControl(new MapboxDraw(), 'bottom-right')

  // 初始化threebox对象并加到全局环境---只能放在这，放在map创建完成后load中模型移动不生效
  // window.tb = new Threebox(map, map.getCanvas().getContext('webgl'), {
  //   defaultLights: true,
  //   // realSunlight: true,
  //   enableSelectingFeatures: true, //模型是否可以被选择
  //   enableSelectingObjects: true, //模型是否可以被选中
  //   enableDraggingObjects: true, //模型是否可以被拖动和移动
  //   enableRotatingObjects: true, //模型是否可以被旋转
  //   enableTooltips: true // 模型是否显示标签
  // })

  // 等map创建完成后加载建筑图层
  map.on('load', function () {
    // 初始化mapbox工具类
    U.init(map)

    // 抛出map创建完成事件
    // emit('onload', map)
    // loadDatas()
    addChartletLyer()
  })
}
const parameter = {
  service: 'WFS',
  version: '1.0.0',
  request: 'GetFeature',
  maxFeatures: '10000',
  outputFormat: 'application/json'
}

// 加载图层数据
async function loadDatas() {
  map.addSource('wms-test-source', {
    type: 'raster',
    // use the tiles option to specify a WMS tile source URL
    // https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/
    tiles: [
      'http://61.52.175.217:8081/geoserver/gwc/service/wmts?layer=zzdx:zzdx_campusmap_baselayer&style=&tilematrixset=EPSG:900913&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix=EPSG:900913:{z}&TileCol={x}&TileRow={y}'
    ],
    tileSize: 256
  })
  map.addLayer({
    id: 'wms-test-layer',
    type: 'raster',
    source: 'wms-test-source',
    paint: {}
  })
}

// 加载贴图建筑
async function addChartletLyer() {
  window.tb = new Threebox(map, map.getCanvas().getContext('webgl'), {
    defaultLights: true
  })
  const parameter = {
    service: 'WFS',
    version: '1.0.0',
    request: 'GetFeature',
    maxFeatures: '10000',
    outputFormat: 'application/json',
    typeName: 'zzdx:building_simple'
  }
  const data = await api.getLayerData('zzdx', parameter).catch((err) => console.log(err))

  // molayersData = layerJson.data
  setTimeout(() => {
    addChartletLayer(data.features)
  }, 100)
}

function addChartletLayer(features) {
  map.addLayer({
    id: 'sqsfchartlet_layer',
    type: 'custom',
    renderingMode: '3d',
    onAdd: function (map, mbxContext) {
      addBuildings(features)
    },
    render: function (gl, matrix) {
      tb.update()
    }
  })
}

function addBuildings(data) {
  data.forEach((b) => {
    if(b.geometry) {
      if(b.geometry.coordinates) {
      // console.log('coordinates', b.geometry.coordinates)
        for (const coordinate of b.geometry.coordinates) {
          const polygon = turf.polygon([coordinate])
          const center = turf.centerOfMass(polygon).geometry.coordinates
          const texture = new THREE.TextureLoader().load(path + 'images/material/floors5.png')
          texture.wrapS = texture.wrapT = THREE.RepeatWrapping
          texture.repeat.set(1, parseInt(b.properties.height / 8)) //重复产生N个相同贴图 产生N行
          // texture.offset.set(0, 0.5)
          const material1 = new THREE.MeshBasicMaterial({
            // color: '#999999',
            transparent: true,
            opacity: 0.7,
            map: texture
          })
          material1.color.offsetHSL(0, 0.5, 0.5)
          const material = new THREE.MeshBasicMaterial({
            color: 'rgb(0,154,153)',
            transparent: true,
            opacity: 1
          })
          material.color.offsetHSL(0, 0.3, 0.3)
          const extrusion = tb.extrusion({
            coordinates: [coordinate],
            geometryOptions: { curveSegments: 1, bevelEnabled: false, depth: b.properties.height / 30 },
            materials: [material, material1]
          })
          // extrusion.addTooltip(b.properties.tooltip, true)
          extrusion.setCoords([center[0], center[1], 0])
          tb.add(extrusion)
        }
      }
    }else{
      console.log('coordinates', b)
    }
  })
}


</script>

<style>
#mapbox-container {
  width: 100vw !important;
  height: 100vh !important;
}
</style>
